package com.bringway.framework.controller;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.bringway.framework.excel.ExcelCell;
import com.bringway.framework.excel.ExcelSheet;
import com.bringway.framework.util.WebUtil;

import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

/*
* @author 作者 xuef
* @version 创建时间：2015年9月9日 下午4:11:17
* 类说明
*/
public class JsonController {
	
	private static Log log = LogFactory.getLog(JsonController.class);
	
	public void serializeToJson(HttpServletRequest request, HttpServletResponse response, JSONObject result)	throws Exception {
		PrintWriter writer = response.getWriter();
		response.setContentType("application/json; charset=UTF-8");
		log.info("result is : " + result.toString());
		writer.write(result.toString());
		writer.flush();
		writer.close();
	}
	
	public void serialize(HttpServletRequest request, HttpServletResponse response, JSONObject result)	throws Exception {
		PrintWriter writer = response.getWriter();
		if(WebUtil.isAjaxRequest(request)){
    		response.setContentType("application/x-json; charset=UTF-8");
    	}else{
    		response.setContentType("text/html; charset=UTF-8");
    	}
		if (log.isDebugEnabled()) {
			log.debug(result.toString());
		}
		log.info("result is : " + result.toString());
		writer.write(result.toString());
		writer.flush();
		writer.close();
	}
	
	public void serialize(HttpServletRequest request, HttpServletResponse response, Object obj)	throws Exception {
		PrintWriter writer = response.getWriter();
		JSONObject result = new JSONObject();
		if(WebUtil.isAjaxRequest(request)){
    		response.setContentType("application/x-json; charset=UTF-8");
    	}else{
    		response.setContentType("text/html; charset=UTF-8");
    	}
		result.put("success", true);
		result.put("data", obj.toString());
		if (log.isDebugEnabled()) {
			log.debug(result.toString());
		}
		System.out.println("result:"+result.toString());
		writer.write(result.toString());
		writer.flush();
		writer.close();
	}
	
	public void serialize(HttpServletRequest request, HttpServletResponse response, List<?> list)	throws Exception {
		PrintWriter writer = response.getWriter();
		JSONObject result = new JSONObject();
		if(WebUtil.isAjaxRequest(request)){
    		response.setContentType("application/x-json; charset=UTF-8");
    	}else{
    		response.setContentType("text/html; charset=UTF-8");
    	}
		result.put("success", true);
		result.put("data", list);
		if (log.isDebugEnabled()) {
			log.debug(result.toString());
		}
		System.out.println("result:"+result.toString());
		writer.write(result.toString());
		writer.flush();
		writer.close();
	}
	
	public void serialize(HttpServletRequest request, HttpServletResponse response, List<?> list, Boolean isOnlyList)	throws Exception {
		PrintWriter writer = response.getWriter();
		String result = JSONArray.fromObject(list).toString();
		if(WebUtil.isAjaxRequest(request)){
    		response.setContentType("application/x-json; charset=UTF-8");
    	}else{
    		response.setContentType("text/html; charset=UTF-8");
    	}
		if (log.isDebugEnabled()) {
			log.debug(result.toString());
		}
		System.out.println("result:"+result.toString());
		writer.write(result.toString());
		writer.flush();
		writer.close();
	}
	
	/**
	 * 下载附件时通用responseHeader
	 * @param response
	 * @param fileName
	 * @throws Exception
	 */
	public static final void setDownLoadResponseHeader(HttpServletRequest request, 
			HttpServletResponse response, String filename) throws Exception {
		if (!response.isCommitted()){
			response.reset();
		}
		response.setContentType("application/x-msdownload");
		String	name = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
        response.setHeader("Content-Disposition", "attachment;filename=" + name);
	}

	/**
	 * @param stencilStream
	 *            Excel模版Stream
	 * @param sheetList
	 *            sheet对象List,其中list里存放ExcelSheet，每个ExcelSheet里存放fromRow(表体从第几行写） @
	 *            sheetName;headList;dataList;
	 * @其中headList 里存放ExcelCell，每个ExcelCell存放x， y， value;
	 * @dataList 里存放一条记录的数组
	 * @param targetUrl
	 *            生成的excel的目标目录(c:\\test1.xls)
	 */
	
	public  void writeToExcelByStencil(InputStream stencilStream,
			List sheetList, OutputStream os) {

		try {
			Workbook wb = Workbook.getWorkbook(stencilStream);

			ByteArrayOutputStream targetFile = new ByteArrayOutputStream();
			WritableWorkbook wwb = Workbook.createWorkbook(targetFile, wb);
			WritableSheet wws = null;

			WritableCellFormat formatTitle = new WritableCellFormat();
	       				WritableFont wfc = new jxl.write.WritableFont(
	       				WritableFont.createFont("宋体"),
	       	            12,
	                    WritableFont.NO_BOLD,
	                    false,
	                    UnderlineStyle.NO_UNDERLINE,
	                    jxl.format.Colour.RED);
	        	
	        	formatTitle.setFont(wfc);
			
			for (int i = 0; i < sheetList.size(); i++) {

				ExcelSheet excelSheet = (ExcelSheet) sheetList.get(i);

				if (sheetList.size() == 1) {
					wws = wwb.getSheet(0);

				} else {
					wws = wwb.getSheet(i);
				}

				List headList = excelSheet.getHeaderList();
				if (headList == null || headList.size() == 0) {

				} else {
					for (int j = 0; j < headList.size(); j++) {

						ExcelCell cell = (ExcelCell) headList.get(j);

						Label label = new Label(cell.getX(), cell.getY(), cell
								.getValue());
						wws.addCell(label);
                    	
				}}

				List dataList = excelSheet.getBodyList();

				if (dataList != null) {

					int readLine = excelSheet.getFromRow();

					for (int k = 0; k < dataList.size(); k++) {

						String lineArr[] = (String[]) dataList.get(k);
						if(lineArr[11]=="否"){
							for (int m = 0; m < lineArr.length; m++) {
									Label cell = new Label(m, readLine + k, lineArr[m],formatTitle);
									wws.addCell(cell);
								}
						}else{
							for (int m = 0; m < lineArr.length; m++) {
								Label cell = new Label(m, readLine + k, lineArr[m]);
								wws.addCell(cell);
							}
						}
						
						
					}
				}

			}
			wwb.write();
			wwb.close();
			wb.close();
			targetFile.writeTo(os);
			targetFile.close();
			// os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
